package com.example.wac.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * @author wuancheng
 * @description
 * @date 2023-05-26 10:24:00
 */

@Component
@Slf4j
public class SignHelper {

    @Value("${sign.secret}")
    private static String SIGN_SECRET;

    /**
     * 获取签名
     *
     * @param signAlgorithm 签名算法 MD2、MD5、SHA-1、SHA-256、SHA-384、SHA-512
     * @param timestamp 时间戳
     * @param reqBodyJsonStr 请求json
     * @return
     */
    public String getSign(String signAlgorithm, String timestamp, String reqBodyJsonStr){
        try {
            String waitSingStr = timestamp + SIGN_SECRET + reqBodyJsonStr;
            // 获取指定签名算法的摘要对象
            MessageDigest messageDigest = MessageDigest.getInstance(signAlgorithm);
            // 重置摘要
            messageDigest.reset();
            // 更新处理摘要
            messageDigest.update(waitSingStr.getBytes());
            // 获取摘要
            String sign = new String(messageDigest.digest(), StandardCharsets.UTF_8);
            return sign;
        } catch (NoSuchAlgorithmException e) {
            log.error("签名失败", e);
        }
        return null;
    }

    /**
     *
     *
     * @param signAlgorithm 签名算法 MD2、MD5、SHA-1、SHA-256、SHA-384、SHA-512
     * @param timestamp 时间戳
     * @param reqBodyJsonStr 请求json
     * @param sign 签名
     * @return
     */
    public boolean checkSign(String signAlgorithm, String timestamp, String reqBodyJsonStr, String sign){
        if (StringUtils.isBlank(sign)) {
            return false;
        }
        String signCheck = getSign(signAlgorithm, timestamp, reqBodyJsonStr);
        return sign.equals(signCheck);
    }

}
